package top.eggcode.system.modules.monitor.message;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import top.eggcode.system.common.consts.Metrics;
import top.eggcode.system.modules.monitor.model.MetricUpload;
import top.eggcode.system.modules.monitor.model.MetricUsage;
import top.eggcode.system.modules.monitor.model.MetricUsageBiz;
import top.eggcode.system.modules.monitor.store.MetricUsageStore;

import java.util.List;

@AllArgsConstructor
@Component
public class MonitorMessageController {

    private final MetricUsageStore metricUsageStore;

    @RabbitListener(queues = "monitor-metric")
    @RabbitHandler
    public void processA(String message) {

        MetricUpload param = JSON.parseObject(message, MetricUpload.class);
        List<MetricUsageBiz> usages = param.getUsages();

        usages.forEach(item -> {
            String metricCode = Metrics.getCode(item.getName());
            String value = item.getValue();
            MetricUsage usage = new MetricUsage();
            usage.init();
            usage.setInstanceId(param.getInstanceId());
            usage.setMetricId(metricCode);
            usage.setValue(value);
            metricUsageStore.save(usage);
        });
    }

}
